<?php
namespace Home\Controller;
use Think\Controller;
use Think\Page;
use Think\Model;

class IndexController extends Controller {
    //商城首页
    public function index(){
        $row = 6;
        //获取新品列表
        $list = M('goods')->where('is_new=1')->page(1,$row)->select();
        $this->assign('list',$list);
        //查询轮播图图片
        $picture = M('lb_picture')->select();
        $this->assign('picture',$picture);
        //获取该用户购物车中单品个数
        $cart_num = $this->cart_num();
        $this->assign('cart_num',$cart_num);
        $this->assign('index',1);  //用来选中底部状态
        $this->display();
    }
    //首页新品上拉加载
    public function upData(){
        $row = 6;
        $page = I('page');
        //上拉加载新品
        $list = M('goods')->where('is_new=1')->page($page,$row)->select();
        if($list){
            echo json_encode($list);
        }else{
            echo -1;
        }
    }

    //商品详情
    public function goods_details(){
        $id = I('goods_id');
        $info = M('goods')->where('good_id='.$id)->find();
        //获取该用户购物车中单品个数
        if(session('user_id') != null){
            $cart_num = M('goods_cart')->where('user_id='.session('user_id'))->count();
        }
        $this->assign('cart_num',$cart_num);
        $this->assign('info',$info);
        $this->display();
    }

    //商品分类
    public function cate(){
        //获取一级分类
        $cate_one = M('good_cate')->field('id,good_cate_name')->where('good_parent_id=0 OR good_parent_id=id')->select();
        //获取二级分类
        $cate_two = M('good_cate')->field('id,good_cate_name,cate_picture')->where('good_parent_id=1')->select();
        $this->assign('cate_one',$cate_one);
        $this->assign('cate_two',$cate_two);
        //获取该用户购物车中单品个数
        $cart_num = $this->cart_num();
        $this->assign('cart_num',$cart_num);
        $this->assign('cate',1);
        $this->display();
    }
    public function cate_two(){
        $where = array(
            'good_parent_id'=>I('cate_id')
        );
        $cate_two = M('good_cate')->field('id,good_cate_name,cate_picture')->where($where)->select();
        echo json_encode($cate_two);
    }

    //获取二级分类下商品
    public function goods(){
        $cate_id = I('cate_id');
        $where = array(
            'cate_id'=>$cate_id
        );
        $search = I('search');
        if($search){
            $where = array(
                'good_name'=>array('like',"%$search%")
            );
        }
        $row = 4;
        $list = M('goods')->where($where)->page(1,$row)->select();
        $this->assign('list',$list);
        //获取该用户购物车中单品个数
        $cart_num = $this->cart_num();
        $this->assign('cart_num',$cart_num);
        $this->assign('cate_id',$cate_id);
        $this->display();
    }

    //分类商品列表页上拉加载
    public function goodsUpdata(){
        $where = array(
            'cate_id'=> I('cate_id'),
        );
        $page = I('page');
        $list = M('goods')->where($where)->page($page,4)->select();
        if($list){
            echo json_encode($list);
        }else{
            echo -1;
        }
    }

    /**
     * 发送手机短信验证码
     */
    public function sendCode()
    {
        $telephone = I('phone');
        if(!checkTelFormat($telephone)){
            echo '手机格式错误';
            exit;
        }
        //判断是否是找回密码
        if(I('type') == 'zhao'){
            $sul = M('user')->field('id')->where('phone='.$telephone)->find();
            if(!$sul){
                echo '用户不存在';   //用户不存在
                exit;
            }
        }
        $code = rand(100000, 999999) . '';//转化成字符串格式
        //将生成的验证码存入数据库
        $mes['code'] = $code;
        $mes['telephone'] = $telephone;
        $mes['sendtime'] = date("Y-m-d H:i:s");
        //将验证码存到数据库
        M('verify')->add($mes);
        $data = array('code' => $code);
        $tpl = "SMS_109545252";
        $mess = sendSms($telephone, $tpl, $data);
        $res = $mess->Code;
        if($res == 'OK'){
            echo '成功';
        }else{
            echo '失败';
        }

    }

    //找回密码--判断验证码是否正确
    public function checkyzm(){
        $phone = I('phone');
        $phonecode = I('code');
        if(!checkTelFormat($phone)){
            echo -2;
            exit;
        }
        $time = date("Y-m-d H:i:s", time() - 600);//十分钟之内有效
        $condition = array(
            'telephone' => $phone,
            "code" => $phonecode,
            "sendtime" => array("GT", $time)
        );
        //判断验证码是否正确
        if(!M('verify')->where($condition)->count()){
            echo -1;  //验证码不正确
        }else{
            echo 1;   
        }
    }

    //加载输入新密码页面
    public function new_pwd(){
        if(IS_AJAX){
            $phone = I('phone');
            $pwd = I('pwd');
            $repwd = I('newpwd');
            $where = array(
                'phone' =>$phone
            );
            $data['password'] = md5($repwd);
            if($pwd != $repwd){
                $this->error('两次密码不一致');
            }
            if(false === M('user')->where($where)->save($data)){
                $this->error('数据异常，请稍后重试');
            }
            $this->success('密码修改成功',U('login'));
        }

        $phone = I('phone');
        $this->assign('phone',$phone);
        $this->display('zhaohui_shurumima');
    }

    //验证手机号是否已注册
    public function checkPhone(){
        $where = array(
            'phone'=>I('phone')
        );
        if(M('user')->field('id')->where($where)->find()){
            echo -1;  //已注册
        }else{
            echo 1;
        }
    }

    //用户注册
    public function reg(){
        $phone = I('phone');
        $phonecode = I('phonecode');
        $password = I('password');
        $repassword = I('repassword');
        if(!checkTelFormat($phone)){
            $this->error('手机格式错误');
        }
        //判断两次密码是否正确
        if($password != $repassword){
            $this->error('两次密码不一致');
        }
        $time = date("Y-m-d H:i:s", time() - 600);//十分钟之内有效
        $condition = array(
            'telephone' => $phone,
            "code" => $phonecode,
            "sendtime" => array("GT", $time)
        );
        //判断验证码是否正确
        if(!M('verify')->where($condition)->count()){
            $this->error('验证码不正确');
        }
        $data['username'] = I('username');
        $data['phone'] = $phone;
        $data['password'] = md5($password);
        $data['add_time'] = date('Y-m-d H:i:s');
        if(M('user')->add($data)){
            $this->success('注册成功',U('login'));
        }else{
            $this->error('数据异常');
        }
    }

    //用户登录
    public function logining(){
        //判断验证码
//        $verify =new \Think\Verify ();
//        if (!$verify->check(I('verifycode'))) {
//            $this->error('验证码不正确');
//        }
        //判断手机号和密码
        $type = I('usertype');
        $where = array(
            'phone' => I('phone'),
            'password' => md5(I('password')),
        );
        if($type == 'user'){  //用户登录
            $info = M('user')->field('id,username,vip,user_type')->where($where)->find();
            if($info){
                session('user_id',$info['id']);
                session('user_name',$info['username']);
                session('vip',$info['vip']);
                session('user_type',$info['user_type']);
                $this->success('登录成功',U('index'));
            }else{
                $this->error('用户名或密码错误');
            }
        }elseif ($type == 'staff'){ //员工登录

        }else{
            $this->error('非法操作');
        }
    }

    //验证码
    public function verify()
    {
        $verify = new \Think\Verify (array(
            'fontSize' => 18,
            'imageH' => 30,
            'imageW' => 110,
            'length' => 3,
            'useCurve' => false,
            'useNoise'=>false,
            'bg'=>array(255,255,255),
            'codeSet'=>'0123456789'
        ));
        $verify->entry();
    }

    //退出登录
    public function login_out(){
        session('user_id',null);
        session('username',null);
        session('vip',null);
        session('user_type',null);
        $this->redirect('Index/index');
    }

    //用户订单列表
    public function order_status(){
        $act = I('act');
        $where['user_id'] = session('user_id');
        switch ($act){
            case 1:
                $where['order_status'] = 1;   //代发货
                break;
            case 2:
                $where['order_status'] = 2;   //代收货
                break;
            case 3:
                $where['order_status'] = 3;   //已完成
                break;
            default:
                $this->error('非法请求');
                break;
        }
        $list = M('order')->where($where)->order('add_time desc')->select();
        $this->assign('list',$list);
        $this->display();
    }

    public function cart(){
        //获取购物车列表
        $list = M('goods_cart gc')->field('gs.good_name,gs.price,gs.vip_price,gs.grade,gs.picture,gc.goods_num,gc.cart_id,gc.goods_id')
            ->join('__GOODS__ gs on gs.good_id=gc.goods_id')
            ->where('user_id='.session('user_id'))
            ->select();
        $this->assign('list',$list);
        $cart_num = $this->cart_num();
        $this->assign('cart_num',$cart_num);
        $this->display();
    }

    //加入购物车
    public function add_cart(){
        $data['user_id'] = session('user_id');
        $data['goods_id'] = I('goods_id');
        $data['goods_num'] = I('goods_num') ? I('goods_num') : 1;
        $data['add_time'] = date('Y-m-d H:i:s',time());
        //判断该商品是否已经加入购物车
        $where = array(
            'user_id'=>session('user_id'),
            'goods_id'=>I('goods_id')
        );
        $res = M('goods_cart')->where($where)->find();
        if($res){
            echo -1;   //表示已经加入
        }else{
            if(M('goods_cart')->add($data)){
                echo 1;
            }else{
                echo -2;
            }
        }

    }

    //购物车删除
    public function cart_del(){
        $cart_id = I('cart_id');
        if(M('goods_cart')->where('cart_id='.$cart_id)->delete()){
            echo 1;  //删除成功
        }else{
            echo -1;  //数据异常
        }
    }

    //修改购物车数量
    public function cart_save(){
        $type = I('type');
        $where = array(
            'cart_id'=>I('cart_id')
        );
        //加
        if($type == 'jia'){
            M('goods_cart')->where($where)->setInc('goods_num');
        }
        //减
        if($type == 'jian'){
            M('goods_cart')->where($where)->setDec('goods_num');
        }
        //手动输入修改数量
        if(I('cart_id') && I('num')){
            M('goods_cart')->where($where)->save(array('goods_num'=>I('num')));
        }

    }

    //购物车结算
    public function payment(){
        $cid = trim(I('cid'),',');
        $condition['user_id'] = session('user_id');
        //如果存在则查询当前收货地址，否则查找默认收货地址
        if(I('addr_id')){
            $condition['address_id'] = I('addr_id');
        }else{
            $condition['status'] = 1;
        }
        //查询默认收货地址
        $default_address = M('area p')
            ->field('ua.*,p.name as province_name,ci.name as city_name,co.name as county_name,tow.name as town_name,u.username')
            ->join('JOIN __USER_ADDRESS__ ua ON p.code = ua.province')
            ->join('JOIN __AREA__ ci ON ci.code = ua.city')
            ->join('JOIN __AREA__ co ON co.code = ua.county')
            ->join('JOIN __AREA__ tow ON tow.code = ua.town')
            ->join('JOIN __USER__ u ON u.id = ua.user_id')
            ->where($condition)
            ->find();

        //判断用户是否有默认地址,没有则加载添加地址页面
        if(!$default_address){
            //查询所有省份
            $province = $this->province();
            $cart_num = $this->cart_num();
            $this->assign('cart_num',$cart_num);
            $this->assign('province',$province);
            $this->assign('cid',$cid);  //购物车结算ID
            $this->display('addaddress');
        }else{
            //查询购物车提交的商品
            $where = array(
                'cart_id'=>array('in',$cid)
            );
            //获取购物车提交的商品
            $list = M('goods_cart gc')->field('g.*,gc.goods_num')
                ->join('__GOODS__ g on g.good_id=gc.goods_id')
                ->where($where)->select();
            //获取计算安装费的配置
            $conf = M('system_config')->where(array('config_id'=>array('in','1,2')))->getField('config_name,config_value');
            //计算总的安装费
            $aloneCount = '';     //单独收取安装费用
            $otherCount = '';     //其他安装费
            $countPrice = '';     //商品总价（不包括安装费）
            foreach ($list as $k=>$v){
                //单独收取安装费
                if($v['alone_install'] ==1){
                    $aloneCount += $v['alone_install_price'] * $v['goods_num'];
                }else{
                    if(session('vip') == 1){
                        $otherCount += $v['vip_price'] * $v['goods_num'] * $conf['install_price_rebate'];
                    }else{
                        $otherCount += $v['price'] * $v['goods_num'] * $conf['install_price_rebate'];
                    }

                }
                if(session('vip') == 1){
                    $countPrice += $v['vip_price'] * $v['goods_num'];
                }else{
                    $countPrice += $v['price'] * $v['goods_num'];
                }
            }
            $count = $aloneCount + $otherCount;
            //判断安装费是否大于最低安装费
            if($count < $conf['min_install_price']){
                $count = $conf['min_install_price'];
            }

            $townList = M('area')->field('code,name')->where('parentId='.$default_address['county'])->select();
            $this->assign('conf',$conf);
            $this->assign('townList',$townList);
            $this->assign('count',$count);
            $this->assign('countPrice',$countPrice);
            $cart_num = $this->cart_num();
            $this->assign('cart_num',$cart_num);
            $this->assign('list',$list);
            $this->assign('cid',$cid);  //购物车结算ID
            $this->assign('default_address',$default_address);
            $this->display();
        }
    }

    //AJAX获取乡镇电工列表
    public function town_electrician_list(){

        $electrician_list = M('electrician as e')
            ->field('e.electrician_id,e.real_name,u.phone,t.name as town_name')
            ->join('JOIN __AREA__ t ON t.code = e.town')
            ->join('JOIN __USER__ u ON u.id = e.electrician_id')
            ->where(array('e.town'=>I('town')))
            ->select();
        echo json_encode($electrician_list);
    }

    //添加收货地址
    public function addaddress(){
        $cid = I('cid');
        //查询所有省份
        $province = $this->province();
        $cart_num = $this->cart_num();
        $this->assign('cart_num',$cart_num);
        $this->assign('province',$province);
        $this->assign('cid',$cid);
        $this->assign('add',1);   //用于标识是用户点击添加新地址
        $this->display();
    }

    //修改收货地址
    public function editaddress(){
        if(IS_POST){
            $data['province'] = I('province');
            $data['city'] = I('city');
            $data['county'] = I('county');
            $data['town'] = I('town');
            $data['detailed_address'] = I('addr');
            $data['receiver'] = I('receiver');
            $data['postcode'] = I('postcode');
            $data['phone'] = I('phone');
            //更新收货地址
            if(false == M('user_address')->where('address_id='.I('addr_id'))->save($data)){
                $this->error('数据异常');
            }else{
                $this->redirect('address',array('cid'=>I('cid')));
            }
        }
        $addr_id = I('addr_id');
        $cid = I('cid');
        //查询收货地址详情
        $info = M('user_address')->where('address_id='.$addr_id)->find();
        //获取所有省份
        $province = $this->province();
        $this->assign('province',$province);
        //查询所在省下的所有市
        $city = M('area')->field('code,name')->where('parentId='.$info['province'])->select();
        $this->assign('city',$city);
        //查询所在市下的所有县
        $county = M('area')->field('code,name')->where('parentId='.$info['city'])->select();
        $this->assign('county',$county);
        //查询所在县下的乡镇
        $town = M('area')->field('code,name')->where('parentId='.$info['county'])->select();
        $this->assign('town',$town);
        $cart_num = $this->cart_num();
        $this->assign('cart_num',$cart_num);
        $this->assign('info',$info);
        $this->assign('cid',$cid);
        $this->display();
    }

    //保存地址操作--跳回订单结算页面
    public function add_address(){
        $data['user_id'] = session('user_id');
        $data['province'] = I('province');
        $data['city'] = I('city');
        $data['county'] = I('county');
        $data['town'] = I('town');
        $data['detailed_address'] = I('addr');
        $data['receiver'] = I('receiver');
        $data['postcode'] = I('postcode');
        $data['phone'] = I('phone');
        $data['status'] = I('status');
        //判断是否有地址，如果没有,自动设为默认地址
        $where = array(
            'user_id'=>session('user_id'),
            'status' =>1
        );
        $status = M('user_address')->field('address_id')->where($where)->find();
        if(!$status){
            $data['status'] = 1;
        }
        //如果有收获地址，并将此次添加设为默认，则先将之前默认取消
        if($status && $data['status']==1){
            M('user_address')->where('user_id='.session('user_id'))->save(array('status'=>0));
        }
        if(M('user_address')->add($data)){
            if(I('add') == 1){   //判断是用户手动点击添加地址
                $this->redirect('address',array('cid'=>I('cid')));
            }else{
                $this->redirect('payment',array('cid'=>I('cid')));
            }
        }else{
            $this->error('数据异常');
        }
    }

    //删除收货地址
    public function address_del(){
        $addr_id = I('addr_id');
        //判断收货地址数量
        $count = M('user_address')->where('user_id='.session('user_id'))->count();
        if($count <= 1){
            echo -1;   //地址只有一个，禁止删除
            exit;
        }
        //判断是否为默认地址
        $info = M('user_address')->field('status')->where('address_id='.$addr_id)->find();
        if($info['status'] == 1){
            echo -2;     //默认地址不能删除
            exit;
        }
        if(M('user_address')->where('address_id='.$addr_id)->delete()){
            echo 1;   //删除成功
        }else{
            echo -3;  //数据异常
        }
    }

    //设为默认收货地址
    public function moren(){
        $model = new Model();
        $model->startTrans();
        //先将之前的默认取消
        $sult = M('user_address')->where('user_id='.session('user_id'))->save(array('status'=>0));
        if($sult == false){
            $model->rollback();
        }
        //将该地址改为默认
        $info = M('user_address')->where('address_id='.I('addr_id'))->save(array('status'=>1));
        if($info == false){
            $model->rollback();
            echo -1;
        }else{
            $model->commit();
            echo 1;
        }
    }

    //获取一级地区
    public function province(){
        $province = M('area')->field('code,name')->where('parentId=0')->select();
        return $province;
    }

    //ajax获取地区
    public function area(){
        $pid = I('pid');
        $area = M('area')->field('code,name')->where(array('parentId' => $pid))->select();
        echo json_encode($area);
    }

    //收货地址列表
    public function address(){
        $cid = I('cid');
        $address_list = M('user_address ua')->field('po.name as province,ci.name as city,co.name as county,tow.name as town,ua.address_id,
        ua.receiver,ua.detailed_address,ua.phone,ua.status')
            ->join('__AREA__ po ON po.code=ua.province')
            ->join('__AREA__ ci ON ci.code=ua.city')
            ->join('__AREA__ co ON co.code=ua.county')
            ->join('__AREA__ tow ON tow.code=ua.town')
            ->where('user_id='.session('user_id'))->select();
        $this->assign('list',$address_list);
        $cart_num = $this->cart_num();
        $this->assign('cart_num',$cart_num);
        $this->assign('cid',$cid);
        $this->display();
    }

    //订单提交
    public function goods_list_zhifu(){
        //微信支付预调用
//        $wxpay = new PayController();
//        $mess = $wxpay -> wxjspay();
//        $this->assign('mess',$mess);

        $cids = trim(I('cid'),',');
        $cid = explode(',',$cids);
        $elec_id = I('diangongid');  //电工id，选就近电工才有值
        $addr_id = I('addr_id');  //收货地址
        //获取收货地址详细信息
        $addrInfo = M('user_address ua')->field('ua.detailed_address,ua.receiver,ua.phone,pr.name as province,ci.name as city,co.name as county,tow.name as town')
            ->join('__AREA__ pr ON pr.code=ua.province')
            ->join('__AREA__ ci ON ci.code=ua.city')
            ->join('__AREA__ co ON co.code=ua.county')
            ->join('__AREA__ tow ON tow.code=ua.town')
            ->where(array('address_id'=>$addr_id))
            ->find();
        $order_number = time().rand(1000,9999);
        //获取安装费配置
        $conf = M('system_config')->where(array('config_id'=>array('in','1,2,5')))->getField('config_name,config_value');

        $goodPrice = '';    //商品总价
        $install_price='';  //总安装费
        $model = new Model();
        $model->startTrans();
        for($i=0;$i<count($cid);$i++){
            //查询商品信息
            $info = M('goods g')->field('g.good_id,g.good_name,g.picture,g.price,g.vip_price,g.grade,gc.goods_num,g.alone_install,g.alone_install_price')
                ->join('__GOODS_CART__ gc on gc.goods_id=g.good_id')
                ->where(array('gc.cart_id'=>$cid[$i]))
                ->find();
            if(!$info){
                $model->rollback();
                $this->error('数据异常');
                exit;
            }

            $data['order_number'] = $order_number;
            $data['user_id'] = session('user_id');
            $data['good_id'] = $info['good_id'];
            $data['good_name'] = $info['good_name'];
            $data['good_picture'] = $info['picture'];
            //如果是会员，存入会员价格
            if(session('vip') == 1){
                $data['price'] = $info['vip_price'];
            }else{
                $data['price'] = $info['price'];
            }
            $data['num'] = $info['goods_num'];
            $data['grade'] = $info['grade'];
            $data['address_id'] = $addr_id;
            $data['add_time'] = date('Y-m_d H:i:s');
            if(I('is_install') == 1){   //如果勾选安装，存储安装费
                $data['is_install'] = 1;
                if($info['alone_install'] == 1){ //单独收取安装费
                    $data['install_price'] = $info['alone_install_price'] * $info['goods_num'];
                }else{
                    //判断是否为会员
                    if(session('vip') == 1){
                        $data['install_price'] = $info['vip_price'] * $info['goods_num'] * $conf['install_price_rebate'];
                    }else{
                        $data['install_price'] = $info['price'] * $info['goods_num'] * $conf['install_price_rebate'];
                    }
                }
            }
            //判断是否选就近安装
            if($elec_id){
                $data['electrician_id'] = $elec_id;
                $data['install_type'] = 2;   //安装方式  2为就近安装
                $data['electrician_confirm'] = 0; //电工是否确认 0为待处理
            }

            if(!M('order')->add($data)){
                $model->rollback();
                $this->error('数据异常');
                exit;
            }
            //计算商品总价
            if(session('vip') == 1){
                $goodPrice += $info['vip_price'] * $info['goods_num'];
            }else{
                $goodPrice += $info['price'] * $info['goods_num'];
            }
            //需要安装计算总安装费
            if(I('is_install') == 1){
                $install_price += $data['install_price'];
            }
        }

        //计算订单总价orderPrice
        if(I('is_install') == 1){
            //判断订单费是否大于最低安装费
            if($install_price < $conf['min_install_price']){
                $orderPrice = $goodPrice + $conf['min_install_price'];
            }else{
                $orderPrice = $goodPrice + $install_price;
            }
        }else{
            $orderPrice = $goodPrice;
        }
        //判断是否选择就近安装
        if($elec_id){
            $orderPrice = $orderPrice * $conf['nearby_install_rebate'];
        }

        //订单生成后，清除购物车
        $delete = M('goods_cart')->where(array('cart_id'=>array('in',$cids)))->delete();
        if(!$delete){
            $model->rollback();
            $this->error('数据异常');
            exit;
        }
        //将订单总价存入订单价格表
        $rus = array(
            'order_number'=>$order_number,
            'order_price'=>$orderPrice,   //订单总价
            'count_price'=>$orderPrice,   //订单总价
        );
        if(!M('count_price')->add($rus)){
            $model->rollback();
            $this->error('数据异常');
            exit;
        }
        $model->commit();

        $this->assign('orderPrice',$orderPrice);
        $this->assign('addrInfo',$addrInfo);
        $this->assign('order_number',$order_number);
        $this->display();
    }

    public function wx_pay(){
        $this->dispaly();
    }

    //查询不同订单状态的条数
    public function order_count($where){
        $order_count = M('order o')->field('cp.order_number,cp.count_price,o.add_time,o.order_status')
            ->join('__COUNT_PRICE__ cp ON cp.order_number=o.order_number')
            ->where($where)
            ->group('o.order_number')
            ->count();
        return $order_count;
    }

    //个人中心
    public function my(){
        //如果登录显示订单条数
        if(session('user_id') != ''){
            //获取待付款订单条数
            $where_not_pay = array(
                'order_status'=>array('in','0,-1'),
                'user_id'=>session('user_id')
            );
            $not_pay_count = $this->order_count($where_not_pay);
            $this->assign('not_pay_count',$not_pay_count);

            //获取待发货订单条数
            $where_not_delivery = array(
                'order_status'=>1, //待发货
                'user_id'=>session('user_id')
            );
            $not_delivery_count = $this->order_count($where_not_delivery);
            $this->assign('not_delivery_count',$not_delivery_count);

            //获取待收货订单条数
            $where_not_receive = array(
                'order_status'=>2, //待收货
                'user_id'=>session('user_id')
            );
            $not_receive_count = $this->order_count($where_not_receive);
            $this->assign('not_receive_count',$not_receive_count);
        }


        //获取该用户购物车中单品个数
        $cart_num = $this->cart_num();
        $this->assign('cart_num',$cart_num);
        $this->assign('my',1);  //用来选中底部变蓝
        $this->display();
    }

    /**
     * 订单状态共用列表
     * @param $where 查询条件
     */
    public function order_list($where){
        $list = M('order o')->field('cp.order_number,cp.count_price,o.add_time,o.order_status')
            ->join('__COUNT_PRICE__ cp ON cp.order_number=o.order_number')
            ->where($where)
            ->group('order_number')
            ->select();
        foreach ($list as $k=>$v){
            //查询订单下的商品图片
            $list[$k]['data'] = M('order o')->field('g.picture')
                ->join('__GOODS__ g on g.good_id=o.good_id')
                ->where('order_number='.$v['order_number'])
                ->select();
        }
        return $list;
    }

    //待支付
    public function wait_pay(){
        if(session('user_id') == null){
            return false;
        }
        $where = array(
            'order_status'=>array('in','0,-1'),
            'user_id'=>session('user_id')
        );
        $list = $this->order_list($where);
        $this->assign('list',$list);
        $cart_num = $this->cart_num();
        $this->assign('cart_num',$cart_num);
        $this->display();
    }

    //代发货列表
    public function orders_payment(){
        if(session('user_id') == null){
            return false;
        }
        $where = array(
            'order_status'=>1, //代发货
            'user_id'=>session('user_id')
        );
        $list = $this->order_list($where);
        $this->assign('list',$list);
        $cart_num = $this->cart_num();
        $this->assign('cart_num',$cart_num);
        $this->display();
    }
    //代收货列表
    public function orders_goodsReceipt(){
        if(session('user_id') == null){
            return false;
        }
        $where = array(
            'order_status'=>2, //待收货
            'user_id'=>session('user_id')
        );
        $list = $this->order_list($where);
        $this->assign('list',$list);
        $cart_num = $this->cart_num();
        $this->assign('cart_num',$cart_num);
        $this->display();
    }
    //已完成列表
    public function orders_complete(){
        if(session('user_id') == null){
            return false;
        }
        $where = array(
            'order_status'=>3, //已完成
            'user_id'=>session('user_id')
        );
        $list = $this->order_list($where);
        $this->assign('list',$list);
        $cart_num = $this->cart_num();
        $this->assign('cart_num',$cart_num);
        $this->display();
    }

    //订单列表页--退换操作
    public function tui_details(){
        $oid = I('oid');
        $where = array(
            'order_number'=>$oid
        );
        //查询订单下详细商品
        $list = M('order')->field('order_id,good_id,good_name,good_picture,price')->where($where)->select();
        $cart_num = $this->cart_num();
        $this->assign('cart_num',$cart_num);
        $this->assign('list',$list);
        $this->display();
    }
    //退换页面信息填写
    public function tuihuo(){
        if(IS_POST){
            $oid = I('order_id');
            $where = array(
                'order_id'=>$oid
            );
            $upload = upload();
            $data['order_status'] = 4;  //申请换货
            $data['apply_return_time'] = date("Y-m-d H:i:s");
            $data['return_reason'] = I('return_reason');  //退换原因
            $data['return_picture'] = json_encode($upload);
            //加入退换货信息
             if(false === M('order')->where($where)->save($data)){
                 $this->error('提交失败，请联系客服');
             }else{
                 $this->success('提交成功',U('orders_complete'));
             }
        }
        $order_id = I('oid');
        //获取商品信息
        $info = M('order')->field('order_id,good_name,good_picture')->where('order_id='.$order_id)->find();
        $this->assign('info',$info);
        $this->display();
    }

    //待抢单列表
    public function qiang(){
        //将电工未同意的就近安装过期订单改为默认抢单
        $time = strtotime("-24 hours");
        $back_time =  date("Y-m-d H:i:s",$time);
        $condition = array(
            'install_type'=>2,
            'electrician_confirm'=>array('neq',1),
            'pay_time'=>array( 'lt',$back_time)
        );
        $data['install_type'] = 1;
        $data['electrician_confirm'] = '';
        $data['electrician_id'] = 0;
        M('order')->where($condition)->save($data);

        //获取所有待安装订单
        $where = array(
            'electrician_id'=>array('eq',0), //没有电工负责的
            'is_install'=>1,    //需要安装的
            'order_status'=>array('in','1,2,3')  //订单状态为代发货、待收货、已收货
        );
        $act = 1;

        //获取所有抢到的订单
        if(I('act') == 2){
            $where = array(
                'electrician_id'=>session('user_id'),
                'is_install'=>1,    //需要安装的
                'install_type'=>'1',//安装类型为系统抢单
            );
            $act = 2;
        }elseif (I('act') == 3){  //指派订单
            $where = array(
                'electrician_id'=>session('user_id'),
                'electrician_confirm'=>array('in','0,1'),  //待处理的
                'install_type' =>2,       //就近安装
                'order_status'=>array('in','1,2,3')  //订单状态为代发货、待收货、已收货
            );
            $act = 3;
        }


        //获取该用户的全部订单
        $order_list = M('order')->where($where)->group('order_number')->select();
        foreach ($order_list as $k=>$v){
            //查询订单下的商品图片
            $order_list[$k]['data'] = M('order o')->field('g.picture')
                ->join('__GOODS__ g on g.good_id=o.good_id')
                ->where('order_number='.$v['order_number'])
                ->select();
        }
        $this->assign('order_list',$order_list);

        //获取该用户购物车中单品个数
        $cart_num = $this->cart_num();
        $this->assign('cart_num',$cart_num);
        $this->assign('qiang',1);//用来选中底部变蓝
        $this->assign('act',$act);//用来选中顶部按钮
        $this->display();
    }

    //抢单操作
    public function qiang_action(){
        $where = array(
            'order_number'=>I('order_number')
        );
        $data['electrician_id'] = session('user_id');
        $data['grab_time'] = date('Y-m-d H:i:s');
        $model = new Model();
        $model->startTrans();
        //判断订单状态，是否已经被抢
        $map = array(
            'order_number'=>I('order_number'),
            'electrician_id'=>array('eq',0)
        );
        if(!M('order')->where($map)->select()){
            echo -2;  //订单已被抢
        }else{
            if(false == M('order')->where($where)->save($data)){
                $model->rollback();
                echo -1;
            }else{
                echo 1;
                $model->commit();
            }
        }
    }

    //安装完成操作
    public function succ_action(){
        $order_number = I('order_number');
        $where = array(
            'order_number'=>$order_number
        );
        $data['install_status'] = 1;
        $data['install_time'] = date('Y-m-d H:i:s');
        //更改订单安装状态
        if(false === M('order')->where($where)->save($data)){
            echo -1;   //操作失败
        }else{
            echo 1;
        }
    }

    //派单确认操作
    public function queren_action(){
        $order_number = I('order_number');
        $where = array(
            'order_number'=>$order_number
        );
        $data['electrician_confirm'] = 1;  //接受
        $data['electrician_confirm_time'] = date('Y-m-d H:i:s');
        //更改订单安装状态
        if(false === M('order')->where($where)->save($data)){
            echo -1;   //操作失败
        }else{
            echo 1;
        }
    }
    //派单取消操作
    public function quxiao_action(){
        $order_number = I('order_number');
        $where = array(
            'order_number'=>$order_number
        );
        $data['install_type'] = 1;
        $data['electrician_confirm'] = -1;
        $data['electrician_confirm_time'] = date('Y-m-d H:i:s');
        $data['electrician_id'] = 0;
        //更改订单安装状态
        if(false === M('order')->where($where)->save($data)){
            echo -1;   //操作失败
        }else{
            echo 1;
        }
    }

    //查看订单详情
    public function orders_details(){
        $order_number = I('oid');
        //获取商品清单
        $list = M('order')->where('order_number='.$order_number)->select();
        $this->assign('list',$list);

        //获取订单基本信息
        $where = array(
            'o.order_number'=>$order_number
        );

        //查询订单详情
        $info = M('order o')->field('o.order_number,o.order_status,o.is_install,o.install_price,o.add_time,ua.detailed_address,ua.receiver,ua.phone')
            ->join('__USER_ADDRESS__ ua on ua.address_id=o.address_id')
            ->where($where)
            ->find();

        //查询是否有优惠减免
        $jian = M('count_price')->field('order_price,count_price')->where('order_number='.$order_number)->find();
        $info['jian'] = $jian['order_price'] - $jian['count_price'];
        //遍历商品清单，算出商品总额
        $count = '';      //商品总额
        $int_price = '';  //安装费
        foreach($list as $k=>$v){
            $count += $v['price']*$v['num'];
            $int_price += $v['install_price'];
        }
        $info['count_price'] = $count;

        //判断是否有安装费,如果有计算安装费
        if($info['is_install'] == 1){
            //查询安装费配置
            $system = M('system_config')->where(array('config_id'=>array('in','1,2')))->getField('config_name,config_value');
            //判断安装费是否低于最低安装费
            if($int_price>$system['min_install_price']){
                $info['install_price'] = $int_price;
            }else{
                $info['install_price'] = $system['min_install_price'];
            }
        }else{
            $info['install_price'] = 0;
        }

        $this->assign('info',$info);


        //获取该用户购物车中单品个数
        $cart_num = $this->cart_num();
        $this->assign('cart_num',$cart_num);
        $this->display();
    }

    //获取购物车数量
    public function cart_num(){
        if(session('user_id') != null){
            $cart_num = M('goods_cart')->where('user_id='.session('user_id'))->count();
        }
        $cart_num = $cart_num ? $cart_num:0;
        return $cart_num;
    }

    //电工注册
    public function electrician(){
        //查询该用户是否提交申请及申请状态
        $info = M('electrician')->field('check_status')->where('electrician_id='.session('user_id'))->find();
        if(IS_POST){
            //判断是否重复提交
            if($info && $info['check_status'] == 0){
                $this->error('申请已提交！请耐心等待',U('index'));
            }
            $data['electrician_id'] = session('user_id');
            $data['real_name'] = I('real_name');
            $data['province'] = I('province');
            $data['city'] = I('city');
            $data['county'] = I('county');
            $data['town'] = I('town');
            $data['id_number'] = I('id_number');
            $data['identity_card_front'] = basePicture(I('identityCardFront'));
            $data['identity_card_reverse'] = basePicture(I('identityCardReverse'));
            $data['electrician_license_front'] = basePicture(I('electricianLicenseFront'));
            $data['electrician_license_reverse'] = basePicture(I('electricianLicenseReverse'));
            $data['add_time'] =date("Y-m-d H:i:s");
            //判断是否为审核失败后提交
            if($info['check_status'] == -1){
                $data['check_status'] = 0;//改为待审核状态
                if(false == M('electrician')->where('electrician_id='.session('user_id'))->save($data)){
                    $this->error('数据异常');
                }else{
                    $this->success('提交成功',U('index'));
                }
            }
            //如果未查到信息则说明第一次申请
            if(!$info){
                if(M('electrician')->add($data)){
                    $this->success('申请成功,请耐心等待',U('index'));
                }else{
                    $this->error('数据异常');
                }
            }
            if(M('electrician')->add($data)){
                $this->success('申请成功，请耐心等待',U('index'));
            }else{
                $this->error('资料填写有误，请重试');
            }
        }
        if($info){
            if($info['check_status'] == -1){
                echo '<script>alert("审核未通过，请重新申请")</script>';
                $province = $this->province();
                $this->assign('province',$province);
                $this->display('zhucediangong');
            }elseif ($info['check_status'] == 0){
                echo '<script>alert("资料审核中，请耐心等待。。。")</script>';
                $this->assign('shenhe',1);
                $this->display('zhucediangong');
            }else{
                $province = $this->province();
                $this->assign('province',$province);
                $this->display('zhucediangong');
            }
        }else{
            $province = $this->province();
            $this->assign('province',$province);
            $this->display('zhucediangong');
        }

    }

    //取消订单
    public function cancel_order(){
        $oid = I('oid');
        $where = array(
            'order_number'=>$oid
        );
        $data = array(
            'order_status'=>-1   //取消
        );
        if(false == M('order')->where($where)->save($data)){

            $this->error('数据异常');
        }else{
            $this->success('订单已取消');
        }
    }

    //确认收货
    public function confirm_order(){
        $oid = I('oid');
        $where = array(
            'order_number'=>$oid
        );
        $data = array(
            'order_status'=>3   //已完成
        );
        if(false == M('order')->where($where)->save($data)){

            $this->error('数据异常');
        }else{
            $this->success('操作成功');
        }
    }

    //待支付页面去支付功能
    public function go_pay(){
        $oid = I('oid');
        $where = array(
            'order_number'=>$oid
        );
        //根据订单编号查询应付金额
        $info = M('count_price')->field('order_number,count_price')->where($where)->find();
        //获取收货地址
        $addrInfo = M('order o')->field('ua.detailed_address,ua.receiver,ua.phone,pr.name as province,ci.name as city,co.name as county,tow.name as town')
            ->join('__USER_ADDRESS__ ua on ua.address_id=o.address_id')
            ->join('__AREA__ pr ON pr.code=ua.province')
            ->join('__AREA__ ci ON ci.code=ua.city')
            ->join('__AREA__ co ON co.code=ua.county')
            ->join('__AREA__ tow ON tow.code=ua.town')
            ->where($where)
            ->find();
        $this->assign('info',$info);
        $this->assign('addrInfo',$addrInfo);
        $this->display();
    }
}